import { Button, Popup, Table } from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";
import { useRequest } from "ahooks";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { AtPagination, AtSearchBar } from "taro-ui";
import {
  getLocationApi,
  getOverdueUserListApi,
} from "../../../servers/servers";
import Taro from "@tarojs/taro";
import CommonTitle from "../../../components/CommonTitle";
import DaySelectPop from "./component/DaySelectPop";
import { Filter } from "@nutui/icons-react-taro";
import { Copy } from "@nutui/icons-react-taro";

const Overdue = () => {
  const [open, setOpen] = useState(false);

  const [total, setTotal] = useState(0);

  /* 当前被查看定位的用户 */
  const [viweUser, setViweUser] = useState("");

  // 查看当前地址
  const [location, setLocation] = useState("");

  const {
    data: batteriesInfo,
    loading,
    runAsync: getLocation,
  } = useRequest(
    async (batteries) => {
      const _res = await getLocationApi({
        batteries,
      });

      return _res;
    },
    {
      manual: true,
    }
  );

  const columns1 = [
    {
      title: "用户号码",
      key: "mobile",
      fixed: "left",
      width: 120,
      render: (_record, index) => {
        return (
          <div   onClick={() => {
            Taro.setClipboardData({
              data: _record?.mobile,
              success: function (res) {
                Taro.getClipboardData({
                  success: function (res) {
                    console.log(res.data); // data
                  },
                });
              },
              fail: function (res) {
                console.log("res", res.errMsg);
              },
            });
          }}>
            {_record?.mobile}{" "}
 
          </div>
        );
      },
    },
    {
      title: "用户姓名",
      key: "name",
      width: 60,
      // fixed: 'left',
    },

    {
      title: "绑定电池",
      key: "binding_batteries",
      width: 230,
    },
    {
      title: "逾期天数",
      key: "overdue_days",
      width: 30,
    },
    {
      title: "到期时间",
      key: "expiration_time",
      render: (_record, index) => {
        return dayjs(_record?.expiration_time).format("YYYY-MM-DD");
      },
      width: 100,
    },
    {
      title: "电池定位",
      key: "service",
      width: 100,
      render: (_record, index) => {
        return (
          <Button
            onClick={async () => {
              const _res = await getLocation(_record?.binding_batteries);
              if (+_res?.code === 0) {
                setOpen(true);
                setViweUser(_record?.name);
                setLocation(_res?.data);
              } else {
                Taro.showToast({
                  title: _res?.msg,
                  icon: "none",
                  duration: 3000,
                });
              }
            }}
          >
            查询定位
          </Button>
        );
      },
    },
  ];
  const [overdueDay, setOverDay] = useState({});

  const { data, run } = useRequest(
    async ({ page, overdue_days__gt, overdue_days__lt, ...ret }) => {
      const _params = {};
      if (ret?.mobile) {
        _params.mobile = ret.mobile;
      }
      if (startDate && endDate) {
        _params.expiration_time__range = [startDate, endDate];
      }
      if (overdue_days__gt) {
        _params.overdue_days__gte = overdue_days__gt * 1;
      }
      if (overdue_days__lt) {
        _params.overdue_days__lte = overdue_days__lt * 1;
      }

      Taro.showLoading({
        title: "加载中",
      });

      try {
        const { data } = await getOverdueUserListApi({
          page,
          filters: JSON.stringify({
            ..._params,
          }),
        });

        setTotal(data?.count);
        Taro.hideLoading();
        return data;
      } catch (error) {
        Taro.hideLoading();
      }
    },
    {
      manual: true,
    }
  );

  // 要搜索的手机号
  const [searchPhone, setSearchPhone] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");

  const [currentPage, setcurrentPage] = useState(1);

  useEffect(() => {
    run({
      page: currentPage,
      mobile: searchPhone,
      start_date: startDate,
      end_date: endDate,
      overdue_days__gt: overdueDay?.overdue_days__gt,
      overdue_days__lt: overdueDay?.overdue_days__lt,
    });
  }, [currentPage, searchPhone, startDate, endDate, overdueDay]);

  const [searchValue, setSearchValue] = useState("");

  const [dayOpen, setDayOpen] = useState(false);

  return (
    <>
      <View
        style={{
          display: "flex",
          alignItems: "center",
        }}
      >
        <View
          style={{
            flex: 1,
          }}
        >
          <AtSearchBar
            showActionButton
            value={searchValue}
            onChange={(val) => {
              setSearchValue(val);
            }}
            onConfirm={(e) => {
              setSearchPhone(e?.target?.value);
            }}
            onActionClick={() => {
              setSearchPhone(searchValue);
            }}
            placeholder="请输入手机号"
            inputType="number"
          />
        </View>
        <DaySelectPop
          open={dayOpen}
          onClose={() => {
            setDayOpen(false);
          }}
          onConfirm={(values) => {
            setOverDay({
              overdue_days__gt: values?.overdue_days__gt,
              overdue_days__lt: values?.overdue_days__lt,
            });

            setDayOpen(false);
          }}
        />
        <Button
          fill="none"
          icon={<Filter />}
          onClick={() => {
            setDayOpen(true);
          }}
        ></Button>

        {/* <FormCalendar
          onConfirm={(values) => {
            setStartDate(dayjs(values?.[0]).format("YYYY-MM-DD HH:mm:ss"));
            setEndDate(
              dayjs(values?.[1])
                .add(23, "hour")
                .add(59, "minute")
                .add(59, "second")
                .format("YYYY-MM-DD HH:mm:ss")
            );
          }}
        /> */}
      </View>

      <Table
        bordered
        striped
        columns={columns1}
        data={data?.list}
        // summary={<>共 {total} 条数据</>}
      />

      <View
        style={{
          display: "flex",
          justifyContent: "center",
          marginTop: 12,
          marginBottom: 12,
        }}
      >
        共 {total} 条数据
      </View>

      <AtPagination
        style={{
          marginTop: 12,
        }}
        total={data?.count}
        pageSize={15}
        current={currentPage}
        onPageChange={(page) => {
          setcurrentPage(page.current);
        }}
      ></AtPagination>

      <Popup
        destroyOnClose
        visible={open}
        position="bottom"
        style={{ height: "500rpx" }}
        onClose={() => {
          setOpen(false);
        }}
      >
        <view
        // style={{
        //   height: "50%",
        // }}
        >
          <View
            className="at-article__h3"
            style={{
              paddingTop: 10,
              paddingBottom: 10,
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            {batteriesInfo?.data?.batteryId}
            <Button
              type="primary"
              onClick={() => {
                Taro.openLocation({
                  latitude: Number(batteriesInfo?.data?.y),
                  longitude: Number(batteriesInfo?.data?.x),
                  scale: 18,
                });
              }}
            >
              导航
            </Button>
          </View>
          <CommonTitle title="电池定位信息" />
          <div
            style={{
              display: "flex",
            }}
          >
            <View className="at-article__p">
              经度：{batteriesInfo?.data?.x}
            </View>
            <View className="at-article__p">
              纬度：{batteriesInfo?.data?.y}
            </View>
          </div>
          <View className="at-article__p">用户姓名：{viweUser}</View>
          <View className="at-article__p">
            更新时间：{batteriesInfo?.data?.updateTime}
          </View>

          {/* <CommonTitle title="电池情况" /> */}
          {/* <Space wrap>
              <Tag background="#E9E9E9" color="#999999">
                当前电压：{batteriesInfo?.data?.currentVoltage}
              </Tag>
              <Tag background="#E9E9E9" color="#999999">
                剩余电量：
                {(
                  Number(batteriesInfo?.data?.currentVoltage) /
                  Number(batteriesInfo?.data?.batteryVoltage)
                ).toFixed(2)}
              </Tag>
              <Tag background="#E9E9E9" color="#999999">
                当前电压：{batteriesInfo?.data?.currentVoltage}
              </Tag>
              <Tag background="#E9E9E9" color="#999999">
                当前电压：{batteriesInfo?.data?.currentVoltage}
              </Tag>
            </Space> */}
          {/* {batteriesInfo?.data?.updateTime ?? "-"}
            <Button onClick={() => setOpen(false)}>关闭</Button> */}
        </view>
      </Popup>
    </>
  );
};
export default Overdue;
